import backtrader as bt
import numpy as np
import numpy as np
import pandas as pd
from scipy import signal   #滤波等
import matplotlib.pyplot as plt
from scipy.signal import find_peaks
#关键点
class KeyPointsInd ():

    def getwave(self, distance,prominence,data,show,ago,size):
        ago = ago if ago is not None else data.buflen()
        size = size if size is not None else data.buflen()
        time = data.datetime
        time_list = time.get(ago=ago, size=size)
        time_list = np.array(time_list)

        #time_list = data..get(ago=ago, size=size)
        high = data.high


        value_list = high.get(ago=ago, size=size)
        value_list = np.array(value_list)

        indices = find_peaks(value_list, height=None, threshold=None, distance=distance,
                             prominence=prominence, width=None, wlen=None, rel_height=None,
                             plateau_size=None)
        stockdata = pd.DataFrame(columns=['val', 'ind', 'type','time'])
        #print(indices)

        val = value_list[indices[0]]
        ind = indices[0]
        if show:
            plt.figure(figsize=(6, 4))
            plt.plot(np.arange(len(value_list)), value_list)
            plt.plot(indices[0], value_list[indices[0]], 'o')
        for i in range(0, len(ind)):
            stockdata = stockdata.append({'val': val[i], 'ind': ind[i], 'type': 1,'time':time_list[ind[i]]}, ignore_index=True)



        low = data.low
        value_list = low.get(ago=ago, size=size)
        value_list = np.array(value_list)
        #print(value_list)
        value_list = value_list*-1
        indices = find_peaks(value_list, height=None, threshold=None, distance=distance,
                             prominence=prominence, width=None, wlen=None, rel_height=None,
                             plateau_size=None)
        #stockdata = pd.DataFrame(columns=['val', 'ind', 'type'])
        val = value_list[indices[0]]
        ind = indices[0]
        value_l = value_list * -1
        if show:
            plt.plot(np.arange(len(value_list)), value_list*-1)
            plt.plot(indices[0], value_l[indices[0]], 'o')
            plt.show()
        for i in range(0, len(ind)):
            #print(ind[i],val[i])
            stockdata = stockdata.append({'val': val[i]*-1, 'ind': ind[i], 'type': 2,'time':time_list[ind[i]]}, ignore_index=True)
        stockdata = stockdata.sort_values(by=['ind'], ascending=False)
        #print(stockdata['val'].min())
        return stockdata

    def next(self):
       try:
        num =len(self.wave)#当前位置
        self.lines.wave[0] = self.wave_value[num-1]
       except Exception as e:
        1 + 1